package com.xnchat.pro.dataStructure;

import java.util.Stack;

/**
 * 简单的练习题
 * 输入一个中缀表达式：如输入 5*2+7-8*2 输出
 * 包含:小于10的非负整数
 * 输出计算结果的值
 * 附加题：带括号的情况
 */
public class TestStack {

    public static void main(String[] args) {
        LinkedListStack symbols = new LinkedListStack();
        Stack<Integer> numbers = new Stack<>();
        //String formula = "6/3+5*2-3*5+9+8/2";
        String formula = "5+2*3-1*4";
        char[] chars = formula.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (isNumber(chars[i])) {
                numbers.push(chars[i] - '0');
                continue;
            } else {
                while (symbols.peek() != '\0' && order(chars[i]) <= order(symbols.peek())) {
                    numbers.push(calculate(symbols.pop(), numbers.pop(), numbers.pop()));
                }
            }
            symbols.push(chars[i]);
        }
        while (symbols.peek() != '\0') {
            numbers.push(calculate(symbols.pop(), numbers.pop(), numbers.pop()));
        }
        System.out.println(numbers.pop());


    }
//运算优先级
    private static int order(char symbol) {
        if ('+' == symbol) return 1;
        if ('-' == symbol) return 1;
        if ('*' == symbol) return 2;
        if ('/' == symbol) return 2;
        return -1;

    }
    //计算
    private static int calculate(char symbol, int num1, int num2) {
        if ('+' == symbol) {
            return num1 + num2;
        }
        if ('-' == symbol) {
            return num2 -num1 ;
        }
        if ('*' == symbol) {
            return num1 * num2;
        }
        if ('/' == symbol) {
            return num2 / num1;
        }
        return 0;
    }
    //判断数字
    private static boolean isNumber(char param) {
        return '0' <= param && param <= '9';
    }
}
